/*
 *  camera.cc
 *  wonderland-project
 *
 *  Created by Ben Nolan on 14/10/08.
 *  Copyright 2008 Nolan Consulting Limited. All rights reserved.
 *
 */

#include "camera.h"

#include <v8.h>
#include <Ogre.h>
#include "vector.h"
#include "quaternion.h"
#include "v8defines.h"
#include "scripting_context.h"

namespace JSCamera{
  
  v8::Handle<v8::ObjectTemplate> instance_template;
  v8::Handle<v8::FunctionTemplate> function_template;
  v8::Persistent<v8::Context> context_;

  V8CALLBACK(Camera,getPosition){ 
    return JSVector::New(V8INTERNAL(Ogre::Camera*)->getPosition());
  }

  V8CALLBACK(Camera,setPosition){ 
    if (!V8ARGUMENTTYPE("Vector", 0))
      return ThrowException(v8::String::New("Invalid argument"));

    V8INTERNAL(Ogre::Camera*)->setPosition(*V8ARGUMENT(Ogre::Vector3*, 0));
    
    return v8::Undefined();
  }

  V8CALLBACK(Camera,getRotation){ 
    return JSQuaternion::New(V8INTERNAL(Ogre::Camera*)->getOrientation());
  }

  V8CALLBACK(Camera,setRotation){ 
    if (!V8ARGUMENTTYPE("Quaternion", 0))
      return ThrowException(v8::String::New("Invalid argument"));

    V8INTERNAL(Ogre::Camera*)->setOrientation(*V8ARGUMENT(Ogre::Quaternion*, 0));
    
    return v8::Undefined();
  }

  V8CALLBACK(Camera,lookAt){ 
    if (!V8ARGUMENTTYPE("Vector", 0))
      return ThrowException(v8::String::New("Invalid argument"));

    V8INTERNAL(Ogre::Camera*)->lookAt(*V8ARGUMENT(Ogre::Vector3*, 0));
    
    return v8::Undefined();
  }

  /* Construct a new camera instance */
  V8CALLBACK(Camera,create){
    v8::Persistent<v8::Object> self = v8::Persistent<v8::Object>::New(args.Holder());
    return self;
  }

  /* Sets internal fields with our idiom of storing the class name in the second field */
  void setInternalFields(v8::Persistent<v8::Object> p, Ogre::Camera *c){
    p->SetInternalField(0, v8::External::New(c));
    p->SetInternalField(1, v8::String::New("Camera"));
  }

  /* Only called from c++ */
  v8::Handle<v8::Value> New(Ogre::Camera *camera){
    context_->Enter();

    v8::Persistent<v8::Object> instance = v8::Persistent<v8::Object>::New(function_template->GetFunction()->NewInstance());
    setInternalFields(instance, camera);
    return instance;
  }

  void Initialize(Wonderland::ScriptingContext *sc){
    context_ = sc->getContext();

    // Function Template
    function_template = v8::FunctionTemplate::New(Camera_create);
    function_template->SetClassName(v8::String::New("Camera"));

    // Instance template
    instance_template = function_template->InstanceTemplate();
    instance_template->SetInternalFieldCount(2);

    #define V8REGISTER(function) instance_template->Set(#function, v8::FunctionTemplate::New(Camera_ ## function));
    
    V8REGISTER(getPosition);
    V8REGISTER(setPosition);
    V8REGISTER(getRotation);
    V8REGISTER(setRotation);
    V8REGISTER(lookAt);
  }

}